package utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Response<T> {
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

    /**
     * 封装返回结果
     *
     * @param response HttpServletResponse
     * @param result   返回结果
     */
    public void render(HttpServletResponse response, Object result) {
        render(response, result, 200); // 默认使用状态码 200
    }

    /**
     * 封装返回结果，并指定状态码
     *
     * @param response HttpServletResponse
     * @param result   返回结果
     * @param status   状态码
     */
    public void render(HttpServletResponse response, Object result, int status) {
        response.setStatus(status); // 设置状态码
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            String jsonResult = gson.toJson(result); // 使用Gson序列化成json字符串
            writer.write(jsonResult);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
